package com.sn.socket.utils;

import java.util.regex.Pattern;

public class FmMsgUtils {

    private static String[] freqs = {"879", "899", "910", "914", "932", "940", "955", "962", "977", "980", "995", "1001", "1017", "1025", "1027", "1037", "1057", "1077"};
    private static int recordSeconds = 30;

    /**
     * parse the client message and return replymessge
     * @param message
     * @return String replymessage
     */
    public static String readMessage(String message) {
        //指令格式:command#freqs#recordseconds, {指令}#{频率}#{录音时长}
        //ex: scanfreqs#870-1080#0  | recording#879#30  # tune#879#0
        String[] msgcontent = message.split("@");
        String reMsg = null;
        if (msgcontent.length < 2) {
            return reMsg;
        }
        switch (msgcontent[1]) {
            case "scanreport":
                freqs = msgcontent[2].split(",");
                reMsg = "recording#" + freqs[0] + "#" + recordSeconds;
                break;
            case "recordreport":
                String currfreq = msgcontent[2].split(",")[0];
                Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
                if (!pattern.matcher(currfreq).matches()) {
                    break;
                }
                int index = getNextIndexFromArray(currfreq, freqs);
                if (index > -1 && index < freqs.length) {
                    reMsg = "recording#" + freqs[index] + "#" + recordSeconds;
                }
                break;
            case "tunefreqreport":

                break;
            case "startreport":
                reMsg = "scanfreqs#870-1080#0";
                break;
            case "devicereport":

                break;
            default:
                break;

        }
        return reMsg;
    }

    /**
     * get index of nex element
     * @param str
     * @param strs
     * @return index of next element
     */
    public static int getNextIndexFromArray(String str, String[] strs) {
        int index = -1;
        if (str == null && str.equals("")) {
            return index;
        }
        for (int i = 0; i < strs.length; i++) {
            if (str.equals(strs[i])) {
                index = i + 1;
                break;
            }
        }
        return index < strs.length ? index : -1;
    }

}
